<template>
  <div class="buypackage-search">
    <el-row :gutter="14" type="flex" justify="start">
      <el-col :span="20">
        <el-input
          v-model="search"
          style="width:200px;"
          placeholder="请输入资产名称"
          @keyup.enter.native="handleFilter"
        />
        <el-button type="primary" icon="el-icon-search" @click="handleFilter">搜索</el-button>
        <el-button size="medium" type="info" @click="clearParams">清空</el-button>
      </el-col>
      <el-col :span="4">
        <div class="shopping-wrap">
          <el-button
            :disabled="size? false: true"
            type="warning"
            icon="el-icon-sold-out"
            @click="showShoppintContent"
          >
            购物车
            <el-badge v-if="size" :value="size" class="badge"/>
          </el-button>
        </div>
      </el-col>
    </el-row>
    <!-- transition 动画特效 -->
    <transition name="el-fade-in-linear">
      <!-- 购物车弹框 -->
      <div v-if="isOpened && size !== 0" class="shopping-content">
        <div v-for="(item, index) in data" :key="index" class="shopping-content-item">
          <div class="shopping-content-item-imgwrap" style="width:180px;">
            <img v-if="item.itemCoverUrl" :src="item.itemCoverUrl" alt>
            <img v-if="!item.itemCoverUrl" src="../../../../assets/subjectImg.png" alt>
          </div>
          <div class="shopping-content-item-title">
            <span class="title">{{ item.name }}</span>
            <span class="close" @click="deleteShoppingItem(item.id)">
              <i class="el-icon-close"/>
            </span>
          </div>
          <div class="shopping-content-item-price">
            ￥{{ item.price }}
            <span>x&nbsp;{{ item.amount }}</span>
          </div>
        </div>
        <div class="shopping-content-submit">
          <span class="shopping-content-submit-total">
            小计
            <span style="font-size:20px;color:#666;">￥{{ total }}</span>
          </span>
          <el-button type="primary" @click="goSettlement">去结算</el-button>
        </div>
      </div>
    </transition>
  </div>
</template>

<script>
  import { unbuyPackageBus } from './eventBus'
  import { addShoppingCarItem, addTransactionRecord, createOrder, deleteShoppingCarItemById, delShoppingCarItems, getShoppingCar, getShoppingCarItemByRelationId } from '@/api/subject/digitalAssets' // 数据接口
  import { getTenantId, getUserId, getUserName } from '@/utils/auth'

  export default {
    data() {
      return {
        radio: '1',
        search: '',
        isOpened: false,
        data: [],
        assetsId: '',
        assetsName: '',
        shoppingCar: '',
        orderId: ''
      }
    },
    computed: {
      total() {
        if (this.data.length) {
          let result = 0
          this.data.forEach(item => {
            if (item.price === 0) {
            } else {
              result += item.price * parseInt(item.amount)
            }
          })
          return result
        }
      },
      size() {
        return this.data.length
      }
    },
    created() {
      this.getShoppingCar()
    },
    beforeDestroy() {
      unbuyPackageBus.$off('addShoppingItem')
    },
    mounted() {
      //接收兄弟元素传值
      unbuyPackageBus.$on('addShoppingItem', (val) => {
        const ret = this.data.find(v => {
          // if (v.itemId === val.id || v.id === val.id) return true
          // if (result) v.count++
          return v.itemName === val.name && v.price === val.price
        })
        if (!ret) {
          this.assetsId += val.id + ','
          this.assetsName += val.name + ','
          val.amount = 1
          addShoppingCarItem(this.madeShoppingCarItem(val)).then(resp => {
            getShoppingCarItemByRelationId(this.shoppingCar.id).then(res => {
              this.data = res.data.items
            })
          })
        }
      })
    },
    methods: {
      handleFilter() {
        unbuyPackageBus.$emit('handleFilter', {search: this.search})
      },
      clearParams() {
        this.search = ''
        unbuyPackageBus.$emit('handleFilter', {search: this.search})
      },
      getShoppingCar() {
        getShoppingCar(getTenantId()).then(res => {
          this.shoppingCar = res.data.item
          this.data = res.data.item.shoppingCarItems
        })
      },
      madeShoppingCarItem(val) {
        const shoppingCarItem = {}
        shoppingCarItem.itemId = val.id
        shoppingCarItem.itemName = val.name
        shoppingCarItem.itemCoverUrl = val.coverUrl
        shoppingCarItem.price = val.price
        shoppingCarItem.amount = val.amount
        shoppingCarItem.totalPrice = val.price
        shoppingCarItem.shoppingCarId = this.shoppingCar.id
        shoppingCarItem.tenantId = getTenantId()
        shoppingCarItem.creator = getUserName()
        return shoppingCarItem
      },
      showShoppintContent() {
        this.isOpened = !this.isOpened
      },
      deleteShoppingItem(id) {
        this.$confirm('确定移除此资产吗?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          deleteShoppingCarItemById(id).then(res => {
            this.getShoppingCar()
            if (this.size === 0) {
              this.isOpened = false
            }
          })
        })
      },
      goSettlement() {
        // 创建订单
        const order = {}
        order.name = getUserName() + '的订单'
        order.totalPrice = this.total
        order.payment = this.total
        order.totalAmount = this.data.length
        order.discountPrice = 0
        order.buyerId = getUserId()
        order.buyerName = getUserName()
        order.creator = getUserName()
        order.tenantId = getTenantId()
        order.shoppingCarId = this.shoppingCar.id
        createOrder(order).then(res => {
          this.orderId = res.data.orderId
          // 创建交易记录
          this.createTransaction()
        })
      },
      createTransaction() {
        const assetsTransaction = {}
        assetsTransaction.tenantId = getTenantId()
        assetsTransaction.purchaserId = getUserId()
        assetsTransaction.purchaserName = getUserName()
        assetsTransaction.transactionPrice = this.total
        assetsTransaction.assetsId = this.assetsId.substring(0, this.assetsId.length - 1)
        assetsTransaction.assetsName = this.assetsName.substring(0, this.assetsName.length - 1)
        assetsTransaction.orderId = this.orderId
        assetsTransaction.assetsCount = this.data.length
        addTransactionRecord(assetsTransaction).then(res => {
          // 清空购物车
          delShoppingCarItems(this.shoppingCar.id).then(r => {
            // 支付页面跳转
            this.$router.push({
              name: 'Classpackage-pay',
              params: {
                'orderId': this.orderId
              }
            })
          })
        })
      }
    }
  }
</script>

<style lang="scss">
  .buypackage-search {
    width: 100%;
    height: 70px;
    line-height: 70px;
    min-width: 1003px;

    .shopping-wrap {
      position: relative;
      width: 100%;
      height: 100%;

      .el-button {
        position: absolute;
        top: 25%;
        right: 0;

        .badge {
          position: absolute;
          top: 0;
        }

        .el-badge__content {
          font-size: 13px !important;
        }
      }
    }

    .shopping-content {
      width: 420px;
      position: absolute;
      right: 20px;
      top: 54px;
      z-index: 25;
      border: 1px solid #999;
      border-radius: 4px;
      padding: 0 20px 10px 20px;
      background-color: #fff;
      box-sizing: border-box;

      &-submit {
        width: 100%;
        height: 50px;
        line-height: 50px;
        position: relative;

        &-total {
          position: absolute;
          left: 0;
          height: 50px;
          line-height: 50px;
          display: block;
        }

        .el-button {
          float: right;
        }
      }

      &-item {
        width: 100%;
        height: 100px;
        line-height: 100px;
        margin-top: 22px;
        position: relative;
        margin-bottom: 18px;

        &-imgwrap {
          width: 110px;
          height: 99px;
          position: absolute;
          left: 0;
          overflow: hidden;

          img {
            height: 100%;
          }
        }

        &-title {
          width: 190px;
          height: 20px;
          line-height: 20px;
          position: absolute;
          right: 0;
          top: 10px;
          font-size: 18px;

          span {
            display: block;
            height: 20px;
            line-height: 20px;
          }

          .title {
            float: left;
          }

          .close {
            float: right;
            width: 20px;
            border-radius: 50%;
            background-color: rgb(202, 202, 202);
            text-align: center;
            color: red;
            cursor: pointer;
          }

          .close:hover {
            opacity: 0.8;
          }
        }

        &-price {
          position: absolute;
          bottom: 40px;
          right: 0;
          width: 190px;
          height: 20px;
          line-height: 20px;
          font-size: 18px;

          span {
            font-size: 16px;
            color: #999;
          }
        }
      }
    }

    ul {
      list-style: none;
      margin: 0;
      padding: 0;
    }
  }
</style>
